package com.ssm.filecontroller;

import com.github.pagehelper.PageInfo;
import com.ssm.dao.IFileDao;
import com.ssm.domain.SysFile;
import com.ssm.service.IFileService;
import com.ssm.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 图片查看控制类
 */
@Controller
@RequestMapping("/file")
public class FileUDController {

    @Autowired
    private IFileDao fileDao;

    /**
     * 查看图片
     * @param fileId
     * @throws Exception
     */
    //TODO
    @RequestMapping("show.do")
    public void show(@RequestParam(name="id") String fileId, HttpServletResponse response) throws Exception {
        SysFile file = fileDao.selectOne(fileId);
        String filepath = file.getFilepath();
        System.out.println("文件路径 " + filepath);

        //使用输入流读取文件
        InputStream fis = new BufferedInputStream(new FileInputStream(new File(filepath)));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();

        String imgSize = String.valueOf(new File(filepath).length());
        //设置response的Header
        //图片大小
        response.addHeader("Content-Length", "" + imgSize);
        OutputStream os = new BufferedOutputStream(response.getOutputStream());

        //图片显示 jpeg、jpg、jpe、jfif新时代图片
        response.setContentType("image/jpeg");

        os.write(buffer);
        os.flush();
        os.close();
    }

}
